<template>
  <t-dialog header="选择图标" :destroy-on-close="true" placement="center" :footer="false" :visible="props.show"
            @close="closeDialog" width="60vw">
    <div class="list-wrapper" ref="list">
      <t-row v-for="(item, index) in allData" :key="index">
        <t-col :span="1" v-for="icon in item" :key="icon.stem" :class="icon.stem === selectedIcon ? 'active' : ''">
          <t-icon :name="icon.stem" size="2em" style="width: 3vw;height: 3vw;margin: 0.5vw"
                  @click="selectIcon(icon.stem)"/>
        </t-col>
      </t-row>
    </div>
  </t-dialog>
</template>

<script setup lang="ts">
import {manifest} from 'tdesign-icons-vue-next'
import {nextTick, ref, type Ref, watch} from "vue";
import {chunkArray} from "@/util/ArrayUtil.ts";

interface Props {
  show: boolean,
  info: string
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  info: ''
})

// 计算1vw的宽度
const viewportWidth = document.documentElement.clientWidth;
const vw = viewportWidth / 100;

const list = ref();
const emit = defineEmits(['select', 'close']);

const selectedIcon: Ref<string> = ref('');
// 构建虚拟滚动
const allData = ref(chunkArray(manifest, 12));

watch(() => props.show, () => {
  if (props.show) {
    const info = props.info;
    if (info != '') {
      selectedIcon.value = info;
      nextTick(() => {
        let index = manifest.findIndex(item => item.stem === info);
        index = Math.floor(index / 12);
        if (index > -1 && list.value) {
          list.value.scrollTop = index * 4 * vw;
        }
      });
    }
  }
})

const selectIcon = (icon: string) => {
  emit("select", icon);
}

const closeDialog = () => {
  emit("close");
}
</script>

<style scoped lang="scss">
.search-input {
  margin-bottom: 10px;
}

.list-wrapper {
  height: 50vh; /* 列表可视区域的高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  position: relative;
}

.active {
  color: var(--td-text-color-brand);
}
</style>